<template>
  <div class="search-source-wrapper">
    <div class="content-main">
      <item-list class="sort-list" :idx="sort"
      :items="sortCover" @changeIdx="changeSort"></item-list>

      <source-list :sources="sourceAbstracts" class="source-list"
      @fetchSourceAbstracts="fetchSourceAbstracts"></source-list>
    </div>

    <div class="help-card" :class="{navScroll: scrollDirection}">
      <screen-card class="filters" 
      :filters="sourceFilters" :query="shapedQuery"
      @chooseFilter="chooseFilter"></screen-card>
      <authority-card class="authority"></authority-card>
    </div>
  </div>
</template>

<script>
import { throttle } from 'lodash'

import ItemList from '@/components/utils/ItemList.vue';
import ScreenCard from './ScreenCard.vue'
import AuthorityCard from '@/components/HelpCard/AuthorityCard.vue'
import SourceList from '@/components/SourceList.vue';

  export default {
    components: {
      ItemList,
      ScreenCard,
      AuthorityCard,
      SourceList
    },    
    data() {
      return {
        scrollDirection: false,
        restrictionNameList: [
          'miw', 'mxw', 'ep', 'f', 'q', 'mis', 'mxs', 's', 't'
        ],
        
        sortCover: ['推荐', '最热', '最新'],
        
        sourceFilters: [
          {
            key: 'ep',
            values: [
              {
                cover: '全部',
                value: 'all'
              },
              {
                cover: '最近一天',
                value: 'd'
              },
              {
                cover: '最近一周',
                value: 'w' 
              },
              {
                cover: '最近一月',
                value: 'm'
              }
            ]
          },
          {
            key: 'mis',
            values: [
              {
                cover: '全部',
                value: 'all'
              },
              {
                cover: '500KB以上',
                value: '500'
              },
              {
                cover: '1MB以上',
                value: '1000'
              },
              {
                cover: '5MB以上',
                value: '5000'
              },
              {
                cover: '10MB以上',
                value: '10000'
              },
            ]
          },
          {
            key: 'mxs',
            values: [
              {
                cover: '全部',
                value: 'all'
              },
              {
                cover: '500KB以下',
                value: '500'
              },
              {
                cover: '1MB以下',
                value: '1000'
              },
              {
                cover: '5MB以下',
                value: '5000'
              },
              {
                cover: '10MB以下',
                value: '10000'
              },
            ]
          }
        ],
        sourceRestrictionAbstractsMap: new Map()
      }
    },
    computed: {
      sort() {
        return parseInt(this.$route.query.s) || 0;
      },
      shapedQuery() {
        let obj = {...this.$route.query};
        let keys = ['miw', 'mxw', 'ep', 'f', 'mis', 'mxs'];
        keys.forEach(key => {
          if(!obj[key]) obj[key] = 'all';
        })
        return obj;
      },
      sourceRestriction() {
        let query = this.$route.query;
        let obj = {
          sort: parseInt(query.s) || 0,
        }
        let types = ['all', 'front', 'back', 'android', 'ios'];
        if(parseInt(query.t)) obj.type = types[query.t];
        Object.keys(query).forEach(key => {
          if(query[key] === 'all') ;
          else {
            let queryDataKeyMap = new Map([
              ['miw', 'minword'],
              ['mxw', 'maxword'],
              ['mis', 'minsize'],
              ['mxs', 'maxsize'],
              ['f', 'file'],
              ['ep', 'expire'],
              ['q', 'keyword'],
            ])
            if(['miw', 'mxw', 'mis', 'mxs'].includes(key)) 
              obj[queryDataKeyMap.get(key)] = parseInt(query[key]);
            if(key === 'f') obj[queryDataKeyMap.get(key)] = query[key] === 't' ? true : false;
            if(key === 'ep') {
              if(query[key] === 'd') {
                obj[queryDataKeyMap.get(key)] = this.$dateUtils.format(Date.now() - 24 * 60 * 60 * 1 * 1000, 'yyyy-MM-dd');
              } else if (query[key] === 'w') {
                obj[queryDataKeyMap.get(key)] = this.$dateUtils.format(Date.now() - 24 * 60 * 60 * 7 * 1000, 'yyyy-MM-dd');
              } else if (query[key] === 'm') {
                obj[queryDataKeyMap.get(key)] = this.$dateUtils.format(Date.now() - 24 * 60 * 60 * 30 * 1000, 'yyyy-MM-dd');
              }
            }
            if(key === 'q') obj[queryDataKeyMap.get(key)] = query[key];
          }
        });
        return obj;
      },
      sourceAbstracts() {
        let map = this.sourceRestrictionAbstractsMap;
        let key = JSON.stringify(this.sourceRestriction);
        if(!map.has(key)) map.set(key, {page: 0, abstracts: []});
        return map.get(key).abstracts;
      }
    },
    methods: {
      chooseFilter(item) {
        this.$router.push({
          path: this.$route.path,
          query: {
            ...this.$route.query,
            [this.sourceFilters[item.filterIdx].key]: this.sourceFilters[item.filterIdx].values[item.idx].value
          }
        });
      },
      changeSort(sort) {
        this.$router.push({
          path: this.$route.path,
          query: {
            ...this.$route.query,
            s: sort
          }
        })
      },
      fetchSourceAbstracts() {
        let restriction = this.sourceRestriction;
        let map = this.sourceRestrictionAbstractsMap;
        let key = JSON.stringify(restriction);
        if(!map.has(key)) map.set(key, {page: 0, abstracts: []});
        let item = map.get(key);
        this.$fetch({
          name: 'source abstracts',
          url: 'source',
          method: 'POST',
          data: {
            page: ++item.page,
            ...restriction
          }
        }).then(res => {
          if(res.data.success) {
            if(res.data.object.length) item.abstracts = item.abstracts.concat(res.data.object);
            else item.page--;
          } else {
            this.$alert({
              type: 'error',
              content: '获取资源内容失败'
            });
            item.page--;
          }
        }).catch(error => {
          this.$alert({
            type: 'error',
            content: '获取资源内容失败'
          });
          item.page--;
        })
      }
    },
    mounted () {
      let beforeY = 0;
      document.addEventListener('scroll', throttle(() => {
        if(window.scrollY - beforeY > 0) {
          this.scrollDirection = true;
        } else {
          this.scrollDirection = false;
        }
        beforeY = window.scrollY
      }, 200));
    },
  }
</script>

<style lang="less" scoped>
@w: var(--innerWidth);
@w1: var(--innerWidthPart1);

.search-source-wrapper {
  .content-main {
    width: @w1;
    background-color: white;

    .sort-list {
      --itemListWidth: calc(@w1 * 0.6);
      --itemListHeight: 50px;
      --itemNum: 3;
    }

    .source-list {
      --sourceListWidth: @w1;
    }
  }

  .help-card {
    position: fixed;
    right: calc((100% - var(--innerWidth)) / 2);
    width: var(--innerWidthPart2);
    transition: .2s;

    .filters {
      --screenCardWidth: var(--innerWidthPart2);
    }

    .authority {
      margin-top: 10px;
      --authorityCardWidth: var(--innerWidthPart2);
    }
  }
}
</style>